﻿using System;
using System.Web;
using System.IO;
using System.Text;

using Fuse8.DomainFramework.Common;

using Fuse8.ContentManagementFramework.SystemFacade.Common;
using Fuse8.ContentManagementFramework.Domain.Bases;

namespace Fuse8.ContentManagementFramework.Web.ApplicationRuntime
{
    public static class EmailService
    {
        public static void Send<T>(BaseEmail<T> emailEntity) where T : class, new()
        {
            Guard.ArgumentNotNull(emailEntity, "emailEntity");

            emailEntity.Prepare();

            if (!string.IsNullOrEmpty(emailEntity.TemplateUrl))
            {
                string templatePath = HttpContext.Current.Server.MapPath(emailEntity.TemplateUrl);

                string template = File.ReadAllText(templatePath, Encoding.UTF8);

                var properties = emailEntity.ReplacementProperties;
                foreach (var property in properties)
                {
                    template = template.Replace(string.Format("**{0}**", property.Key), property.Value);
                }

                emailEntity.Body = template;
            }

            EmailSender.SendMessage(emailEntity.From, emailEntity.To, emailEntity.Bcc, emailEntity.Subject, emailEntity.Body, null);
        }
    }
}
